package com.diors.game.engine.arpg.scene;

import java.util.concurrent.atomic.AtomicInteger;

import com.diors.game.engine.arpg.fight.attr.AttrEnum;
import com.diors.game.engine.arpg.fight.attr.object.AttrObject;
import com.diors.game.engine.arpg.object.AbstractObject;
import com.diors.game.engine.arpg.scene.entity.Position;
import com.diors.game.engine.arpg.scene.entity.SceneObject;


/**
 * 地图工具类
 * @author	darren.ouyang <ouyang.darren@gmail.com>
 * @date	2013年11月11日
 * @version 1.0
 * @copyright Copyright (c) 2013, darren.ouyang
 */
public final class MapUtils 
{
	
	private final static MapUtils instance = new MapUtils();
	
	private AtomicInteger sceneID = new AtomicInteger();
	
	private AtomicInteger mapID = new AtomicInteger();
	
	private MapUtils (){}
	
	public static MapUtils getInstance ()
	{
		return instance;
	}
	
	/**
	 * 生成场景ID
	 * @return
	 * @author	darren.ouyang
	 * @create	2013年11月13日 上午10:07:36
	 */
	public int createSceneID ()
	{
		return sceneID.incrementAndGet();
	}
	
	/**
	 * 生成地图ID
	 * @return
	 * @author	darren.ouyang
	 * @create	2013年11月13日 上午10:07:20
	 */
	public int createMapID ()
	{
		return mapID.incrementAndGet();
	}
	
	/*public ScreenEntity getScreen (MapEntity map)
	{
		
	}*/
	
	
	public Position getNowPos (AbstractObject object, long time)
	{
		/* 如果当前不在移动,当前点等于当前点 */
		SceneObject sceneObject = object.getSceneObject();
		Position pos = sceneObject.getPos();
		Position targetPos = sceneObject.getTargetPos();
		if (targetPos == null)
			return pos;
		
		int dirX = targetPos.getX() - pos.getX();
		int dirY = targetPos.getY() - pos.getY();
		
		/* 如果目标点等于当前点 */
		if (dirX == 0 && dirY == 0)
		{
			sceneObject.setTargetPos(null);
			return pos;
		}
		
		/* 获取移动时间 */
		long lastMvTime = sceneObject.getLastMvTime();
		long mvTime = lastMvTime - time;
		if (mvTime <= 500l)
			return pos;
		
		AttrObject attrObject = object.getAttr();
		float mv = attrObject.getValueFloat(AttrEnum.MV);
		double distance = countDistance(targetPos.getX(), targetPos.getY(), pos.getX(), pos.getY());
		double realDistance = (double)(mv * mvTime * SceneConfig.MV_RATIO);
		if (distance <= realDistance)
		{
			sceneObject.setPos(targetPos);
			sceneObject.setTargetPos(null);
			return targetPos;
		} 
		
		double ratio = realDistance/distance;
		pos = new Position((int)(ratio * dirX), (int)(ratio * dirY));
		sceneObject.setPos(pos);
		return pos;
	}

	/**
	 * 计算2点间距离(返回像素)
	 * @param sx
	 * @param sy
	 * @param tx
	 * @param ty
	 * @return
	 * @author	darren.ouyang
	 * @create	2013年11月12日 上午11:16:58
	 */
	public static double countDistance(int sx, int sy, int tx, int ty) 
	{
		return Math.sqrt(Math.pow((sx - tx), 2) + Math.pow((sy - ty), 2));
	}
}
